// 内置数据集弹框
import React, { Component, createContext } from 'react'
import { Table, Input, Button, Modal, notification, Upload, Popconfirm, message } from 'antd';
import styles from '@/pages/algorithmModel/dataCenter/style.less';
import { baseUrl } from '@/utils/config.js'
import { checkBeforeFileUpload } from '@/utils/utils'
// import { getBuildInDatasetList, deleteBuildInDataSet, addBuildInDataSet, getBuildInVersionDataSetList } from '@/services/modelCenter1';
// marked
import { getBuildInDatasetList, deleteBuildInDataSet, addBuildInDataSet, getBuildInVersionDataSetList } from '@/services/modelCenter';

import { getDataPurpose, getDataSetList, } from '@/services/dataCenter';
import style from '../style.less'
import { lowerFirst } from 'lodash';

const { Search } = Input;
class InsertDataSet extends Component {
    constructor(props) {
        super(props);
        const { modelId ,insertData} = this.props;

        this.state = {
            // 内置数据集数量
            insertData,
            // 表格数据源
            dataList: [],
            loading: false,
            // 模型列表 从后端获取
            modelList: [],
            // 模型id
            modelId,
            // 文件列表
            fileList: [],
            disabled: false,
        };
    }

    componentDidMount() {
        getDataPurpose({ commonType: 'model_purpose' }).then(rs => {
            if (rs.retCode === '0') {
                this.setState({ modelList: rs.data })
            }
        });
        this.queryDataSet();
    }

    // 获取数据集列表
    queryDataSet(dataSetName) {
        const { modelId, } = this.state;
        const { isVersion, versionId } = this.props;
        (isVersion ? getBuildInVersionDataSetList({ data: { modelId, versionId, dataSetName }, pageNum: 0, pageSize:0 }) : getBuildInDatasetList({ data: { modelId, dataSetName }, pageNum:0, pageSize: 0 })).then(res => {
            if (res.retCode === '0') {
                this.setState({ dataList: res.data.list, });
            }
        })
    }

    // 提交上传的数据集
    submit() {
        const { modelId, fileList, loading } = this.state;
        if (fileList.length > 0) {
            this.setState({ loading: true });
            const formData = new FormData();
            fileList.forEach(file => {
                formData.append('files', file);
            });
            formData.append('modelId', modelId);
            addBuildInDataSet(formData).then(res => {
                if (res.retCode === '0') {
                    this.props.parent.showInsertData(false);
                    this.props.parent.queryModelList();
                }else{
                    this.setState({ loading: false });
                }
            })
        } else {
            message.error('请先上传数据集');
        }
    }

    // 搜索数据集列表
    onDataSetSearch(val) {
        this.queryDataSet(val);
    }

    // 删除内置数据集
    deleteDataSet(dataSetId) {
        const { modelId } = this.state;
        deleteBuildInDataSet(dataSetId, modelId).then(res => {
            if (res.retCode === '0') {
                this.queryDataSet();
            }
        })
    }


    render() {
        const { loading, dataList, modelList, fileList, disabled ,insertData} = this.state;
        const { visible, isVersion, } = this.props;
        const props = {
            multiple: true,
            onRemove: file => {
                this.setState(state => {
                    const index = state.fileList.indexOf(file);
                    const newFileList = state.fileList.slice();
                    newFileList.splice(index, 1);
                    return {
                        fileList: newFileList,
                    };
                });
            },
            beforeUpload: (file, fileLists) => {
                let find = fileList.find(item => item.name === file.name);
                let isAcceptFileType = checkBeforeFileUpload(file, ['json']);
                if (!isAcceptFileType.tip) {
                    notification['warning']({
                        message: '警告',
                        key: isAcceptFileType.msg,
                        description: isAcceptFileType.msg
                    });
                    return true;
                }
                if (find) {
                    notification['warning']({
                        message: '警告',
                        key: '存在同名文件',
                        description: '存在同名文件'
                    });
                    return true;
                } else {
                    if (fileLists.length > 5 - this.state.fileList.length) {
                        notification['warning']({
                            message: '警告',
                            key: '每次上传文件个数不超过5个',
                            description: '每次上传文件个数不超过5个'
                        });
                        return true;
                    } else {
                        this.setState(state => ({
                            fileList: [...state.fileList, file],
                        }));
                        return false;
                    }
                }
            },
            fileList,
        };
        let columns = [
            { title: '名称', dataIndex: 'dataSetName', key: 'dataSetName' },
            {
                title: '上传时间', dataIndex: 'createTimeShort', key: 'createTimeShort', width: 160,
            },
            {
                title: '操作',
                key: 'actions',
                width: 160,
                render: record => <span>
                    <Popconfirm
                        title="确定删除?"
                        okText="确定"
                        cancelText="取消"
                        onConfirm={this.deleteDataSet.bind(this, record.dataSetId)}
                    >
                        <a type="link">删除</a>
                    </Popconfirm>
                </span>,
            },
        ];
        isVersion && columns.splice(columns.length - 1, 1);

        return (
            <Modal
                title={'内置数据集'}
                maskClosable={false}
                width={'40%'}
                visible={visible}
                onCancel={() => this.props.parent.showInsertData(false)}
                footer={!isVersion ? [
                    <Button key="cancel" onClick={() => this.props.parent.showInsertData(false)}>取消</Button>,
                    <Button key="primary" type='primary' loading={loading} onClick={this.submit.bind(this)}>确定</Button>
                ] : null}
            >
                {!isVersion && <div style={{ marginBottom: 10 }}>
                    <span className={style.uploadFile}>
                        <Upload {...props} accept=".json" style={{ position: 'relative' }}>
                            <Button size='small' type='primary' disabled={disabled}> + 上传 </Button>
                        </Upload>
                    </span>
                    <span className={style.text}>支持扩展名：.json ,<a target='_blank' download={'模板'} className="ant-dropdown-link" type='link' href={baseUrl + '/templates/model_build_in'}>下载模板说明</a></span>
                </div>}
                {( insertData || isVersion) &&
                    <><Search placeholder="搜索名称" onSearch={value => this.onDataSetSearch(value)} style={{ width: 200, marginBottom: 16 }} />
                        <Table columns={columns} dataSource={dataList} size='small' rowKey={record => record.dataSetId}
                            pagination={{ pageSize:5 }}
                        />
                    </>}
            </Modal>
        )
    }
}

export default InsertDataSet;
